package com.tanhua.management.api.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.intern.InternUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.jdbc.StringUtils;
import com.tanhua.common.mapper.AdminRoleMapper;
import com.tanhua.common.mapper.LogMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.AdminRole;
import com.tanhua.common.pojo.Log;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.management.api.CustomerApi;
import com.tanhua.management.vo.ClientVo;
import com.tanhua.management.vo.CustomerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CustomerApiImpl implements CustomerApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Reference
    private UserLikeApi userLikeApi;


    @Override
    public PageInfo<CustomerVo> findall(Integer page, Integer pageSize) {
        PageInfo<CustomerVo> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

       //按照更新时间排序
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("updated");

        List<CustomerVo> customerVoList = this.select(page, pageSize, queryWrapper);
        pageInfo.setRecords(customerVoList);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        pageInfo.setTotal(userInfoList.size());

        return pageInfo;
    }

    @Override
    public PageInfo<CustomerVo> findById(Integer page, Integer pageSize, String id) {
        PageInfo<CustomerVo> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("user_id",id)
                .orderByDesc("updated");

        List<CustomerVo> customerVoList = this.select(page, pageSize, queryWrapper);
        pageInfo.setRecords(customerVoList);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        pageInfo.setTotal(userInfoList.size());

        return pageInfo;
    }
    //昵称查询
    @Override
    public PageInfo<CustomerVo> findByNickname(Integer page, Integer pageSize, String nickname) {
        PageInfo<CustomerVo> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("nick_name",nickname)
                .orderByDesc("updated");

        List<CustomerVo> customerVoList = this.select(page, pageSize, queryWrapper);

        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        pageInfo.setTotal(userInfoList.size());
        pageInfo.setRecords(customerVoList);

        return pageInfo;
    }

    @Override
    public PageInfo<CustomerVo> findByCity(Integer page, Integer pageSize, String city) {
        PageInfo<CustomerVo> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("city",city)
                .orderByDesc("updated");

        List<CustomerVo> customerVoList = this.select(page, pageSize, queryWrapper);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        pageInfo.setTotal(userInfoList.size());
        pageInfo.setRecords(customerVoList);

        return pageInfo;
    }

    @Override
    public PageInfo<CustomerVo> findByIdNickname(Integer page, Integer pageSize, String id, String nickname) {
        PageInfo<CustomerVo> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);


        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.and(i->i.like("user_id",id).ne("nick_name",nickname))
                .orderByDesc("updated");

        List<CustomerVo> customerVoList = this.select(page, pageSize, queryWrapper);

        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        pageInfo.setTotal(userInfoList.size());
        pageInfo.setRecords(customerVoList);

        return pageInfo;
    }

    /**
     * 第二个接口
     * 返回个人信息
     * @param userId
     * @return
     */
    @Override
    public ClientVo findClientVo(String userId) {
        ClientVo clientVo = new ClientVo();

        UserInfo record = this.userInfoMapper.selectById(userId);

        clientVo.setId(Convert.toInt(userId));
        String logo = record.getLogo();
        clientVo.setLogo(logo);

        String nickName = record.getNickName();
        clientVo.setNickname(nickName);
        //用户电话
        User user = userMapper.selectById(record.getUserId());
        clientVo.setMobile(user.getMobile());
        //性别，年龄，职业
        clientVo.setSex(record.getSex().getValue() == 1 ? "man" : "women");
        clientVo.setAge(record.getAge());
        clientVo.setOccupation(record.getIndustry());
        //用户状态
        QueryWrapper<AdminRole> query=new QueryWrapper<>();
        query.eq("user_id",record.getUserId());
        AdminRole adminRole = adminRoleMapper.selectOne(query);
        //用户状态
        Integer state = adminRole.getState();
        clientVo.setUserStatus(String.valueOf(state));
        //最近活跃时间
        clientVo.setLastActiveTim(50);
        //城市，标签
        clientVo.setCity(record.getCity());
        clientVo.setTags(record.getTags());
        //收入
        clientVo.setIncome(Convert.toInt(record.getIncome()));
        //最近登录地
        Log log = logMapper.selectById(userId);
        clientVo.setLastLoginLocation(log.getPlace());
        //互相喜欢
        Query query1=Query.query(Criteria.where("userId").is(Long.valueOf(userId)));
        long countMatching = this.mongoTemplate.count(query1, Users.class);
        //被喜欢，
        Query query2=Query.query(Criteria.where("likeUserId").is(Long.valueOf(userId)));
        long countBelike = this.mongoTemplate.count(query2, UserLike.class);
        //喜欢
        Query query3=Query.query(Criteria.where("userId").is(Long.valueOf(userId)));
        long countliked = this.mongoTemplate.count(query3, UserLike.class);

        clientVo.setCountMatching(Convert.toInt(countMatching));
        clientVo.setCountLiked(Convert.toInt(countliked));
        clientVo.setCountBeLiked(Convert.toInt(countBelike));
        //个性签名
        clientVo.setPersonalSignature("生如夏花之绚烂,死如秋叶之静美");
        return clientVo;
    }


    /**
     * 分页查询数据并封装
     *
     * @param page
     * @param pageSize
     * @param queryWrapper
     * @return
     */

    private List<CustomerVo> select(Integer page, Integer pageSize,QueryWrapper<UserInfo> queryWrapper){

        IPage<UserInfo> pages = new Page<>(page,pageSize);
        pages = this.userInfoMapper.selectPage(pages, queryWrapper);
        List<CustomerVo> customerVoList=new ArrayList<>();
        List<UserInfo> records = pages.getRecords();

        for (UserInfo record : records) {
            CustomerVo customerVo = new CustomerVo();
            customerVo.setId(Convert.toInt(record.getUserId()));
            String logo = record.getLogo();
            customerVo.setLogo(logo);
            //头像状态
            if (null!=logo){
                customerVo.setLogoStatus("1");
            }else{
                customerVo.setLogoStatus("2");
            }
            String nickName = record.getNickName();
            customerVo.setNickname(nickName);
            //用户电话
            User user = userMapper.selectById(record.getUserId());
            String mobile = user.getMobile();
            customerVo.setMobile(mobile);

            customerVo.setSex(String.valueOf(record.getSex().getValue()));
            customerVo.setAge(record.getAge());
            customerVo.setOccupation(record.getIndustry());
            //用户状态
            QueryWrapper<AdminRole> query=new QueryWrapper<>();
            query.eq("user_id",record.getUserId());
            AdminRole adminRole = adminRoleMapper.selectOne(query);
            Integer state = adminRole.getState();
            customerVo.setUserStatus(String.valueOf(state));
            //最近活跃时间
            customerVo.setLastActiveTim(50);
            customerVo.setCity(record.getCity());

            customerVoList.add(customerVo);
        }

        return customerVoList;
    }
}
